package com.apkcore.core.net

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

class RetrofitProvider {

    companion object {
        const val CONNECTION_TIME_OUT = 10L
        const val READ_TIME_OUT = 10L
    }

    private lateinit var retrofit: Retrofit

    fun initialize(baseUrl: String, interceptors: List<Interceptor> = emptyList(),
                   connectTimeout:Long= CONNECTION_TIME_OUT,readTimeout:Long= READ_TIME_OUT) {
        val clientBuilder = OkHttpClient.Builder()
        val logging = HttpLoggingInterceptor()
        logging.level = HttpLoggingInterceptor.Level.BODY
        clientBuilder.addInterceptor(logging)
        for (interceptor in interceptors) {
            clientBuilder.addInterceptor(interceptor)
        }
        clientBuilder.connectTimeout(connectTimeout, TimeUnit.SECONDS)
            .readTimeout(readTimeout, TimeUnit.SECONDS).proxy(Proxy.NO_PROXY)
        clientBuilder.sslSocketFactory(
            SSLNoCheckClient.getSSLSocketFactory(), SSLNoCheckClient.getX509TrustManager()
        ).hostnameVerifier(SSLNoCheckClient.getHostnameVerifier())

        retrofit = buildRetrofit(baseUrl, clientBuilder)
    }

    private fun buildRetrofit(baseUrl: String, builder: OkHttpClient.Builder): Retrofit {
        val client = builder.build()
//        val contentType = "application/json".toMediaType()
//        val json = Json {
////            prettyPrint = true  //漂亮的 Json 格式
//            isLenient = true  //宽松的解析
//            ignoreUnknownKeys = true  //忽略未知键
//            coerceInputValues = true  //空时强制使用默认值
//        }
        return Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(GsonConverterFactory.create())
//            .addConverterFactory(json.asConverterFactory(contentType))
            .client(client).build()
    }

    private var mApi: Any? = null

    fun<T> createService(serviceClass: Class<T>): T {
        if (!::retrofit.isInitialized) {
            throw IllegalStateException("RetrofitProvider is not initialized. Call initialize() first.")
        }
        if (mApi == null) {
            synchronized(this) {
                if (mApi == null) {
                    mApi = retrofit.create(serviceClass)
                }
            }
        }
        return mApi!! as T
    }
}